<!--页面交互逻辑不复杂的弹出选择框  查看核销示例-->
<template>
  <div class='divandpro'>
    <j-modal
      :title='name'
      width='100%'
      :visible='display'
      switchFullscreen
      @cancel='close'
      cancelText='关闭'>
      <template slot='footer'>
        <a-button @click='close'>取消</a-button>
        <a-button type='primary' @click='handleOk'>确认</a-button>
      </template>
      <!--        <div id="movebox"   @click="handleMove(e)"  class="movebox">-->
      <a-row :gutter='18'>
        <a-col :span='24'>
          <!-- 查询区域 -->
          <!--          <div class="table-page-search-wrapper">-->
          <!--            <a-form layout="inline" @keyup.enter.native="searchQuery">-->
          <!--              <a-row :gutter="24">-->
          <!--                <a-col :xl="8" :lg="7" :md="8" :sm="24" v-for="(item,index) in formconfig" :key="index">-->
          <!--                  <a-form-item :label=item.label>-->
          <!--                    <a-input :placeholder="'请输入' + item.label" v-model="queryParam[item.key]"></a-input>-->
          <!--                  </a-form-item>-->
          <!--                </a-col>-->
          <!--                <div style="float: left;overflow: hidden;" class="table-page-search-submitButtons">-->
          <!--                  <a-col :xl="6" :lg="7" :md="8" :sm="24">-->
          <!--                    <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>-->
          <!--                    <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>-->
          <!--                  </a-col>-->
          <!--                </div>-->
          <!--              </a-row>-->
          <!--            </a-form>-->
          <!--          </div>-->
          <a-table
            size='small'
            bordered
            ref='table'
            :columns='columns'
            tableLayout='auto'
            :dataSource='dataSource'
            :pagination='false'
            :loading='loading'
            :scroll='{ x: "max-content",y:500 }'
            @change='handleTableChange'>
            <!--            rowKey='id'-->
            <span slot='urlPath' slot-scope='t,r,index'>
               <a v-if='r.files.length < 1'>暂无</a>
              <a v-filesDownLoad='r.files' v-if='r.files.length >= 1'>{{ r.exampleNames }} </a>
            </span>
            <span slot='action' slot-scope='text, record, index'>
                            <div v-if='!unOrDown'>
                            <a v-filesDownLoad='(record.files)' v-if='record.files.length >= 1'>点击下载</a>
                                <div v-if='record.files.length < 1'>暂无附件</div>
                            </div>
                            <div v-if='unOrDown'>
                              <div>
                                 <div class='file-box' v-if='unOrDown && unDownUrl'>
                                  <a>{{ record.fileName || '点击上传' }}</a>
                                 <input type='file' @change='e=> tableUnloadP(e,record)' class='file-btn' />
                              </div>
                              <span>{{ record.name }}</span>
                              </div>
                              <div v-if='unOrDown && !unDownUrl'>
                                 <a v-downLoad='{urlPath:record.urlPath,fileName:record.fileName}'
                                    v-if='record.urlPath'>{{ record.fileName }}</a>
                                <div v-if='!record.urlPath'>暂无附件</div>
                              </div>
                            </div>
                          </span>
          </a-table>
        </a-col>
        <!--        <a-col :span="8">-->
        <!--          <a-card :title="'已选' + name" :bordered="false" :head-style="{padding:0}" :body-style="{padding:0}">-->
        <!--            <a-table size="middle" :rowKey="rowKey" bordered v-bind="selectedTable" :columns="innerColumns">-->

        <!--            </a-table>-->
        <!--          </a-card>-->
        <!--        </a-col>-->
      </a-row>
    </j-modal>
  </div>
</template>

<script>
import 'viewerjs/dist/viewer.css'
import { Cascader } from 'ant-design-vue'
import Ellipsis from '@comp/ellipsis'
import { PageListMixin } from '@/mixins/PageListMixin'
import { cloneObject, pushIfNotExist } from '@/utils/util'
import lodash from 'lodash'
import { getAction, postAction } from '@api/manage'
import { filterObj } from '@/utils/util'
import { filesDownLoad, downLoad } from '@/directive/downLoadUrl'
// 动态计算需要合并的单元格的行
export default {
  name: 'writeExample',
  mixins: [PageListMixin],
  directives: { filesDownLoad, downLoad },
  components: { Ellipsis, Cascader },
  props: {
    // 下载/上传
    unDownUrl: {
      type: Boolean,
      default: false
    },
    unOrDown: {
      type: Boolean,
      default: false
    },
    value: {
      type: Array,
      default: () => []
    },
    checkVal: {
      type: Function | Object
    },
    visible: {
      type: Boolean,
      default: false
    },
    // multiple: {
    //   type: Boolean,
    //   default: true
    // },
    width: {
      type: Number,
      default: 900
    },
    name: {
      type: String,
      default: '核销示例'
    },
    // 添加商品的回传

    // listUrl: {
    //   type: String,
    //   required: true,
    //   default: ''
    // },
    // 根据 value 获取显示文本的地址，例如存的是 username，可以通过该地址获取到 realname
    valueUrl: {
      type: String,
      default: ''
    },
    displayKey: {
      type: String,
      default: null
    },
    // 查询条件Code
    queryParamCode: {
      type: String,
      default: null
    },
    // 查询条件文字
    queryParamText: {
      type: String,
      default: null
    },
    // rowKey: {
    //   type: String,
    //   default: 'id'
    // },
    // 过长裁剪长度，设置为 -1 代表不裁剪
    ellipsisLength: {
      type: Number,
      default: 12
    }
  },
  data() {
    return {
      images: [],
      temp: {},
      formData: '',
      fileBook: '',
      fileName: '',
      columW: 4,
      multiple: true,
      display: false,
      valueKey: '',
      innerValue: [],
      // 已选择列表
      selectedTable: {
        pagination: false,
        scroll: {
          y: 240
        },
        dataSource: []
      },
      renderEllipsis: (value) => (<ellipsis length={this.ellipsisLength}>{value}</ellipsis>),
      url: {
        list: null
        // treedata: window._CONFIG['domianURL'] + '/cnProductTypeController/getProductTypeTree'
      },
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 5,
        pageSizeOptions: ['5', '10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      options: [],
      dataSourceMap: {},
      formconfig: [],
      tableconfig: {},
      status: null,
      status2: null,
      isorter: {}
    }
  },
  watch: {
    'checkVal': {
      deep: true,
      immediate: true,
      handler(val) {
        this.$nextTick(() => {
          if (val && !lodash.isEmpty(val)) this.$set(this, 'queryParam', val)
        })
      }
    },
    value: {
      deep: true,
      immediate: true,
      handler(val) {
        this.$nextTick(() => {
          this.innerValue = cloneObject(val)
          this.selectedRowKeys = []
          this.valueWatchHandler(val)

          // this.queryOptionsByValue(val)
        })
      }
    },
    // dataSource: {
    //   deep: true,
    //   handler(val) {
    //     this.emitOptions(val)
    //     this.valueWatchHandler(this.innerValue)
    //   }
    // },
    selectedRowKeys: {
      immediate: true,
      deep: true,
      handler(val) {
        this.selectedTable.dataSource = val.map(key => {
          for (let data of this.dataSource) {
            if (data[this.rowKey] === key) {
              pushIfNotExist(this.innerValue, data[this.valueKey])
              return data
            }
          }
          for (let data of this.selectedTable.dataSource) {
            if (data[this.rowKey] === key) {
              pushIfNotExist(this.innerValue, data[this.valueKey])
              return data
            }
          }
          console.warn('未找到选择的行信息，key：' + key)
          return {}
        })
      }
    }
  },
  methods: {
    tableEdit(r) {
      this.images = [r.urlPath]
    },
    mergeCells(text, array, columns) {
      if (!array || array.length == 0) {
        return
      }
      let i = 0
      if (text !== this.temp[columns]) {
        this.temp[columns] = text
        array.forEach((item) => {
          if (item[columns] === this.temp[columns]) {
            i += 1
          }
        })
      }
      console.log(columns + ':' + i)
      return i
    },
    tableUnloadP(e, e2) {
      let that = this
      const dataSource = [...this.dataSource]
      const target = dataSource.find(item => item == e2)
      if (target) {
        this.fileBook = e.target.files[0]
        this.fileName = e.target.files[0].name
        this.formData = new FormData()
        this.formData.append('file', this.fileBook)
        let url = window._CONFIG['domianUploadURL'] + '/cnUploadController/uploadLocal'
        postAction(url, this.formData).then(res => {
          if (!res.success) {
            this.$message.error(res.message)
          } else {
            target.fileName = res.result.fileName
            target.urlPath = res.result.url
            this.temp = {}
            that.$set(that, 'dataSource', dataSource)
          }
        })
      }

      console.log(e)
      console.log(e2)
    },
    logsdisappear(code) {
      console.log(code)
    },
    // 重置数据
    searchReset() {
      this.queryParam = {}
      this.loadData(1)
    },
    getQueryParams() {
      //高级查询器  数据采集
      let sqp = {}
      if (this.superQueryParams) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams)
        sqp['superQueryMatchType'] = this.superQueryMatchType
      }
      let param = Object.assign(sqp, this.queryParam, this.isorter, this.filters)
      console.log(param)
      param.field = this.getQueryField()
      param.current = this.ipagination.current
      param.size = this.ipagination.pageSize
      delete param.birthdayRange //范围参数不传递后台
      return filterObj(param)
    },
    // 获取树状数据  status:name  status2:code  datasource, 回显的数组数据
    edit(formconfig, tableconfig) {
      this.dataSource = []
      this.tableconfig = Object.assign({}, tableconfig)
      if (!this.url.list || this.url.list !== this.tableconfig.list) {
        this.url.list = this.tableconfig.list
        this.queryParam = {}
        this.loadData()
      } else {
        this.loadData()
      }
      this.$nextTick(() => {
        this.multiple = tableconfig.multiple
        tableconfig.columW ? this.columW = tableconfig.columW : this.columW = 4
      })
      this.display = true
    },

    // 需要带值查询事件
    searchData() {

    },
    /** 关闭弹窗 */
    close() {
      this.display = false
    },

    valueWatchHandler(val) {
      val.forEach(item => {
        this.dataSource.concat(this.selectedTable.dataSource).forEach(data => {
          if (data[this.valueKey] === item) {
            pushIfNotExist(this.selectedRowKeys, data[this.rowKey])
          }
        })
      })
    },
    getParams() {
      const params = this.checkVal || {}
      for (let key of Object.keys(params)) {
        if (key && (params[key] === undefined || params[key] === '')) {
          return false
        }
      }
      return this.lodash.isEmpty(params) ? true : params
    },

    queryOptionsByValue(value) {
      console.log(this)
      const params = this.getParams()
      if (!params) return
      if (typeof params === 'boolean' && params) {
        if (!value || value.length === 0) {
          return
        }
        // 判断options是否存在value，如果已存在数据就不再请求后台了
        let notExist = false
        for (let val of value) {
          let find = false
          for (let option of this.options) {
            if (val === option.value) {
              find = true
              break
            }
          }
          if (!find) {
            notExist = true
            break
          }
        }
        if (!notExist) return
      }
      postAction(this.url.list, {
        // 这里最后加一个 , 的原因是因为无论如何都要使用 in 查询，防止后台进行了模糊匹配，导致查询结果不准确
        // [this.valueKey]: value.join(',') + ',',
        pageNo: 1,
        pageSize: value.length,
        ...params
      }).then((res) => {
        if (res.success) {
          let dataSource = res.result
          if (!(dataSource instanceof Array)) {
            dataSource = res.result.records
          }
          this.emitOptions(dataSource, (data) => {
            pushIfNotExist(this.innerValue, data[this.valueKey])
            pushIfNotExist(this.selectedRowKeys, data[this.rowKey])
            pushIfNotExist(this.selectedTable.dataSource, data, this.rowKey)
          })
        }
      })
    },

    emitOptions(dataSource, callback) {
      dataSource.forEach(data => {
        let key = data[this.valueKey]
        this.dataSourceMap[key] = data
        pushIfNotExist(this.options, { label: data[this.displayKey], value: key }, 'value')
        typeof callback === 'function' ? callback(data) : ''
      })
      this.$emit('options', this.options, this.dataSourceMap)
    },
// 鼠标移动事件

    /** 完成选择 */
    handleOk() {
      let selectionRows = JSON.parse(JSON.stringify(this.selectionRows))
      this.$emit('okbro', selectionRows, this.status, this.status2, this.dataSource)
      this.selectedTable.dataSource = []
      this.selectedRowKeys = []
      this.selectionRows = []
      this.isorter = {}
      this.close()
    },

    /** 删除已选择的 */
    handleDeleteSelected(record, index) {
      this.selectedRowKeys.splice(this.selectedRowKeys.indexOf(record[this.rowKey]), 1)
      this.selectionRows.splice(this.selectionRows.indexOf(record), 1)
      this.selectedTable.dataSource.splice(index, 1)
    },

    customRowFn(record) {
      return {
        on: {
          click: () => {
            console.log(this.rowKey)
            let key = record[this.rowKey]
            if (!this.multiple) {
              this.selectedRowKeys = [key]
              this.selectionRows = [record]
              // this.selectedTable.dataSource = [record]
            } else {
              let index = this.selectedRowKeys.indexOf(key)
              if (index === -1) {
                this.selectedRowKeys.push(key)
                this.selectionRows.push(record)
                // this.selectedTable.dataSource.push(record)
              } else {
                this.handleDeleteSelected(record, index)
              }
            }
          }
        }
      }
    },
    loadData(arg) {
      if (!this.url || !this.url.list) {
        // this.$message.error("请设置url.list属性!")
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      let params = this.getQueryParams()//查询条件
      this.loading = true
      let request = null
      let isNoPagnation = ['getDictByCode'].some(url => new RegExp(`${url}$`).test(this.url.list))
      if (isNoPagnation) {
        request = getAction
      } else {
        request = postAction
      }
      var that = this

      params.ways == 'get' ? request = getAction : request = postAction
      return request(this.url.list, params).then((res) => {
        if (res.success) {
          this.temp = {}
          that.dataSource = res.result
          res.result.records ? this.dataSource = res.result.records : this.dataSource = res.result
          // 处理示例名称

          this.dataSource.forEach(item => {
            item.exampleNames = item.files.map(item => {
              return item.fileName
            }).join(',')
          })

          console.log(this.dataSource)
          if (!isNoPagnation) that.ipagination.total = res.result.total || 0

        } else {
          that.$message.warning(res.message)
        }
        that.loading = false
      })
    }

  },
  created() {
    this.columns = [
      {
        title: '活动细类名称',
        align: 'center',
        dataIndex: 'categoriesDetailName',
        width: 110,
        customRender: (text, row, index) => {
          if (text != '') {
            const obj = {
              children: text,
              attrs: {}
            }
            obj.attrs.rowSpan = this.mergeCells(row.categoriesDetailName, this.dataSource, 'categoriesDetailName')
            return obj
          }
        }
      },
      { title: '核销要求资料', width: 100, align: 'center', dataIndex: 'exampleName' },
      // { title: '描述', align: 'center', width: 100, dataIndex: 'remarks' },
      // { title: '示例', align: 'center', width: 100, dataIndex: 'urlPath', scopedSlots: { customRender: 'urlPath' } },
      // {
      //   title: '是否必填', align: 'center', width: 40, dataIndex: 'isRequire',
      //   customRender: (t) => {
      //     if (t == 1) {
      //       return '是'
      //     } else if (t == 0) {
      //       return '否'
      //     }
      //   }
      // },
      { title: '操作', align: 'center', width: 100, dataIndex: 'action', scopedSlots: { customRender: 'action' } }
    ]
  }

}
</script>

<style scoped lang='less'>
.divandpro {
  background-color: #fff;

  .buttonadd {
    margin: 2px 0 0 15px;
    box-shadow: 0 0 3px 3px rgb(205, 205, 205);
    height: 40px;
    width: 40px;
  }

  .buttonadd:hover {
    box-shadow: 0 0 5px 5px rgb(205, 205, 205);
  }

  .addsadd {
    transform: translateX(-4px);
  }
}

.productlog {
  width: 90%;
  color: red;
  border: 1px solid rgb(205, 205, 205);
  padding: 2px 0 2px 4px;
  border-radius: 5px;
  box-sizing: border-box;
}

.productlog:hover {
  border: 1px solid rgb(2, 14, 225);

}

.file-box {
  position: relative;
  opacity: 1;
}

.file-btn {
  width: 100%;
  opacity: 0;
  position: absolute;
  z-index: 2;
  left: 0;
  top: 0;
  height: 100%;
}


</style>